﻿using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;

namespace DataServices
{
	public class WcfDataService : DataService<NorthwindEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }

		[WebGet]
		public IQueryable<Order> GetOrdersByCity(string city)
		{
			if (string.IsNullOrEmpty(city))
			{
				throw new ArgumentNullException("city",
					"You must provide a value for the parameter'city'.");
			}

			// Get the ObjectContext that is the data source for the service.
			NorthwindEntities context = this.CurrentDataSource;

			try
			{

				var selectedOrders = from order in context.Orders.Include("Order_Details")
									 where order.Customer.City == city
									 select order;

				return selectedOrders;
			}
			catch (Exception ex)
			{
				throw new ApplicationException("An error occured: {0}", ex);
			}
		}
    }
}
